<template>
  <div style="margin: 10px;height: 100vh"      v-loading="spinning">
    <JzTable v-model:jzTableData="jzTableData"
             v-model:handleSelectionChangeData="handleSelectionChangeData"
             v-model:queryFormInlineSubmit="queryFormInlineSubmit"
             @refreshClick="refreshClick"

    >
      <!--    查询表单-->
      <template v-slot:showQuery>

        <el-form ref="formRef" :inline="true"
                 :model="queryFormInline" class="demo-form-inline"
                 style="padding-left: 20px;padding-right: 20px;padding-top: 10px;">

          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="queryFormInline.roleName" placeholder="请输入角色名称" clearable/>
          </el-form-item>

          <el-form-item label="状态" prop="roleState">
            <el-select
                v-model="queryFormInline.roleState"
                placeholder="请选择"
                clearable
                style="width: 100px"
            >
              <el-option label="启用" value="NORMAL"/>
              <el-option label="停用" value="STOP"/>
            </el-select>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" @click="submitForm">搜索</el-button>
            <el-button @click="resetForm(formRef)">重置</el-button>
          </el-form-item>
        </el-form>

      </template>


      <!--    按钮组-->
      <template v-slot:buttonGroup>
        <el-button type="primary" @click="roleSaveOrUpdateShow('')" plain>
          新增
        </el-button>

        <el-button type="success" @click="roleSaveOrUpdateShow(handleSelectionChangeData[0].id)" :icon="Edit" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].roleName=='超级管理员')"  plain>
          修改
        </el-button>
        <el-button type="primary" @click="dialogVisible=true;sysMsg='确定要启用【'+handleSelectionChangeData[0].roleName+'】角色';sysOperateType='updateRoleState';sysOperateId=handleSelectionChangeData[0].id;":icon="Open" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&(handleSelectionChangeData[0].roleState!='STOP'||handleSelectionChangeData[0].roleName=='超级管理员'))"  plain>
          启用
        </el-button>

        <el-button type="warning" @click="dialogVisible=true;sysMsg='确定要停用【'+handleSelectionChangeData[0].roleName+'】角色';sysOperateType='updateRoleState';sysOperateId=handleSelectionChangeData[0].id;" :icon="TurnOff" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&(handleSelectionChangeData[0].roleState!='NORMAL'||handleSelectionChangeData[0].roleName=='超级管理员'))"  plain>
          停用
        </el-button>
        <el-button type="danger" @click="dialogVisible=true;sysMsg='确定要删除【'+handleSelectionChangeData[0].roleName+'】角色';sysOperateType='deleteConfirm';sysOperateId=handleSelectionChangeData[0].id;" :icon="Delete" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1|| (handleSelectionChangeData.length==1&&handleSelectionChangeData[0].roleName=='超级管理员')" plain>
          删除
        </el-button>

      </template>

      <template v-slot:tableColumn>
        <el-table-column type="selection"  width="55"  />
        <el-table-column type="index" :index="1" :fixed="'left'" label="序号"/>
        <template v-for="item in jzTableData.jzTable.zjColumnList">
          <template v-if="item.show">
            <el-table-column :label="item.label" v-if="item.prop=='roleStateTagEnumBean'" :sortable="item.sortable?'custom':false" :show-overflow-tooltip="true">
              <template #default="scope">
                <el-tag :type="scope.row.roleStateTagEnumBean.style.type" round>{{
                    scope.row.roleStateTagEnumBean.msg
                  }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column :prop="item.prop" :label="item.label" :sortable="item.sortable?'custom':false"  :show-overflow-tooltip="true" v-else />

          </template>
        </template>

        <el-table-column fixed="right" label="操作">
          <template #default="scope">

            <el-button
                size="small"
                v-if="scope.row.userName!='admin'"
                link type="success"
                @click=" roleSaveOrUpdateShow(scope.row.id)"
                style="margin-right: 2px"
                :icon="Edit"
            >
              修改
            </el-button>





            <el-button link  size="small" v-if="scope.row.roleState=='STOP'&&scope.row.pid!='0'" type="primary" @click="dialogVisible=true;sysMsg='确定要启用【'+scope.row.roleName+'】角色';sysOperateType='updateRoleState';sysOperateId=scope.row.id;":icon="Open"  plain>
              启用
            </el-button>

            <el-button link  size="small" v-if="scope.row.roleState=='NORMAL'&&scope.row.pid!='0'" type="warning" @click="dialogVisible=true;sysMsg='确定要停用【'+scope.row.roleName+'】角色';sysOperateType='updateRoleState';sysOperateId=scope.row.id;" :icon="TurnOff" plain>
              停用
            </el-button>
            <el-button link  size="small"   v-if="scope.row.roleName!='超级管理员'" type="danger" @click="dialogVisible=true;sysMsg='确定要删除【'+scope.row.roleName+'】角色';sysOperateType='deleteConfirm';sysOperateId=scope.row.id;" :icon="Delete"  plain>
              删除
            </el-button>


          </template>


        </el-table-column>
      </template>

    </JzTable>

  <el-dialog v-model="saveOrUpdateOpen" :title="saveUpdateTitle" width="800" style="z-index: 999">
    <el-form :model="roleSaveOrUpdateParam" label-width="auto" style="max-width: 800px"
             ref="roleSaveOrUpdateRef"
             :rules="roleSaveOrUpdateRules"
    >

      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleSaveOrUpdateParam.roleName" clearable/>
      </el-form-item>

      <el-form-item label="排序" prop="roleSort">
        <el-input-number v-model="roleSaveOrUpdateParam.roleSort" :min="1" :max="99"/>
      </el-form-item>
      <el-form-item label="备注" prop="roleRemarks">
        <el-input v-model="roleSaveOrUpdateParam.roleRemarks" clearable/>
      </el-form-item>

      <el-form-item label="菜单权限" prop="menuIds">
        <el-scrollbar height="200px" style="width: 100% ">
          <el-tree
              style="width: 100% !important;"
              :props="{children: 'childMenuListVOs', label: 'menuName', id: 'id', class: customNodeClass }"
              :data="menuTreeData"
              node-key="id"
              :highlight-current="true"
              :key="treeKey"
              :check-strictly="false"
              show-checkbox
              ref="menuTree"
          >
            <template #default="{ node, data }">
        <span class="custom-tree-node">
           <el-text class="mx-1" :type="node.data.menuTypeTagEnumBean.style.type"> {{ node.label }}</el-text>
       </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveSubmit(roleSaveOrUpdateRef)" v-if="updateRoleId==''" :loading="spinning">添加</el-button>
        <el-button type="primary" @click="updateSubmit(roleSaveOrUpdateRef)" v-if="updateRoleId!=''" :loading="spinning">修改</el-button>
        <el-button @click="saveOrUpdateOpen = false">取消</el-button>
      </div>
    </template>

  </el-dialog>

    <el-dialog
        v-model="dialogVisible"
        title="系统提示"
        width="500"
        align-center
    >
      <span>{{sysMsg}}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sysOperate()" :loading="spinning">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>

import {onMounted, ref, toRaw, reactive, watch, type Ref, type UnwrapRef} from 'vue'
import request from "@/api/request";
import JzTable from "@/components/jiaoZi/table/JzTable.vue";
import {jzTableData, type ZjColumn} from "@/components/jiaoZi/table/JzTable";

import {type ElDialog, ElMessage, type FormInstance, type FormRules} from "element-plus";
import {RoleFromInfo, type RoleSaveOrUpdateParam, roleSaveOrUpdateParam} from "@/views/sys/role/RoleInfo";
import {Delete, Edit, Open, TurnOff, View} from "@element-plus/icons-vue";


const roleSaveOrUpdateRef = ref<FormInstance>()
const roleSaveOrUpdateRules = reactive<FormRules<RoleSaveOrUpdateParam>>({
  roleName: [
    {required: true, message: '请填写角色名称', trigger: 'blur'}
  ],
  roleRemarks: [
    {required: true, message: '请填写备注', trigger: 'blur'}
  ]
});


let spinning = ref<boolean>(false);
//添加修改是否可见弹窗
let saveOrUpdateOpen = ref<boolean>(false)
//修改的角色id
let updateRoleId = ref<string>("");
//弹窗标题
let saveUpdateTitle = ref<string>("添加角色");


//菜单树
let menuTreeData = ref([]);
let menuTree = ref(null);
let menuTreeCheckStrictly = ref<boolean>(false)
const formRef = ref<FormInstance>()
const treeKey = ref(0);

let handleSelectionChangeData=ref();

let dialogVisible = ref<boolean>(false);
let sysMsg = ref("");
let sysOperateType=ref("");
let sysOperateId=ref("");


function sysOperate(){
  spinning.value = true;
  if(sysOperateType.value=="deleteConfirm"){
    deleteConfirm(sysOperateId.value)
  }else if(sysOperateType.value=="updateRoleState"){
    updateRoleState(sysOperateId.value)
  }


}


interface Tree {
  id: number
  label: string
  isPenultimate?: boolean
  children?: Tree[],
  menuType: string
}

// :props="{children: 'childMenuListVOs', label: 'menuName', id: 'id'}"
const customNodeClass = (data: Tree, node: Node) => {
  if (data.menuType == "MENU") {
    return 'is-penultimate'
  }
  return null
}


//查询条件
let queryFormInline = ref({
  roleName: '',
  roleState: '',
  columnOrder:{}
})



//查询条件点击提交的时候绑定
let queryFormInlineSubmit: any = toRaw({
  roleName: '',
  roleState: '',
  zjOrderProp:'',
  zjSortOrder:'',
})


onMounted(() => {
  //初始化
  getInfo();
  //加载默认数据
  getPage();
  //加载菜单数据
  getMenuList();
  // columnsInfo();
})




//删除角色信息
const deleteConfirm = (id: any) => {

  request.delete('/sysRole/' + id).then((res: any) => {
    spinning.value = false;
    dialogVisible.value = false
    // queryFormInlineSubmit.value=null;
    if (res.code == '10000') {
      ElMessage.success("删除成功");
      getPage();
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })
};



//打开修改窗体
function roleSaveOrUpdateShow(id: string) {
  treeKey.value++;
  spinning.value = true;
  if (id == null || id == '') {
    RoleFromInfo(null)
    updateRoleId.value = "";
    saveUpdateTitle = ref("添加角色信息");
    saveOrUpdateOpen.value = true;
    spinning.value = false;
  } else {
    request.get('/sysRole/' + id).then((res: any) => {
      if (res.code == '10000') {
        saveOrUpdateOpen.value = true;
        saveUpdateTitle.value = "修改角色信息";
        updateRoleId.value = id;
        RoleFromInfo(res.data);
        menuTree.value.setCheckedKeys(res.data.menuIds, false)
        if(res.data.menuIsNullIds!=null){
          for (const element of res.data.menuIsNullIds) {
            menuTree.value.setChecked(element, false, false)
          }
        }

      } else {
        ElMessage.error(res.errorMessage);
        saveOrUpdateOpen.value = false;
      }
      spinning.value = false;
    }).catch((error) => {
      console.log(error)
      spinning.value = false;
      saveOrUpdateOpen.value = false;
    })
    menuTreeCheckStrictly.value = false;
  }
}

//查询条件提交
const submitForm = () => {
  jzTableData.value.jzPageData.current = 1;
  queryFormInlineSubmit = JSON.parse(JSON.stringify(queryFormInline.value));
  getPage();

}

//重置查询条件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 添加角色信息
const saveSubmit = async (formEl: FormInstance | undefined) => {
  if (menuTree) {
    roleSaveOrUpdateParam.menuIds = []
    roleSaveOrUpdateParam.menuIds.push(...menuTree.value.getCheckedKeys());
    roleSaveOrUpdateParam.menuIds.push(...menuTree.value.getHalfCheckedKeys());
  }
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      spinning.value = true;
      request.post('/sysRole/', roleSaveOrUpdateParam).then((res: any) => {
        spinning.value = false;

        if (res.code == '10000') {
          saveOrUpdateOpen.value = false;
          ElMessage.success("添加成功");
          getPage();

        }else {
          ElMessage.error(res.errorMessage);
          spinning.value = false;
        }
      }).catch((error) => {
        console.log( error)
        spinning.value = false;
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

//更新角色信息
const updateSubmit = async (formEl: FormInstance | undefined) => {
  if (menuTree) {
    roleSaveOrUpdateParam.menuIds.length = 0;
    roleSaveOrUpdateParam.menuIds.push(...menuTree.value.getCheckedKeys());
    roleSaveOrUpdateParam.menuIds.push(...menuTree.value.getHalfCheckedKeys());

  }
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      spinning.value = true;
      request.put('/sysRole/' + updateRoleId.value, roleSaveOrUpdateParam).then((res: any) => {

        if (res.code == '10000') {
          ElMessage.success("修改成功");
          saveOrUpdateOpen.value = false;
          getPage();
        } else {
          ElMessage.error(res.errorMessage);
          spinning.value = false;
        }
      }).catch((error) => {
        console.log( error)
        spinning.value = false;
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}



function refreshClick() {
  getPage()
}


function getInfo(){
  request.get('/sysRole/info' ).then((res: any) => {
    if (res.code == '10000') {
      jzTableData.value.jzTable=res.data;
      let columnAll=jzTableData.value.jzTable.zjColumnList;
      jzTableData.value.jzTable.zjColumnList =columnAll.filter((tab) => tab.show == true)
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    console.log(error)
  })
}



function getMenuList() {

  request.get('/sysMenu/menuListTree').then((res: any) => {
    if (res.code == '10000') {
      menuTreeData.value = res.data.menuListVOS;
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    console.log(error)
  })
}


function getPage() {
  spinning.value = true;
  request.get('/sysRole/page/' + jzTableData.value.jzPageData.current + '/' + jzTableData.value.jzPageData.size, {params: queryFormInlineSubmit}).then((res: any) => {
    spinning.value = false;
    queryFormInlineSubmit.value = null;
    if (res.code == '10000') {
      jzTableData.value.jzPageData = res.data;
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
    console.log(error)
  })
}


function updateRoleState(id: string) {
  spinning.value = true;
  request.put('/sysRole/updateRoleState/' + id).then((res: any) => {
    if (res.code == '10000') {
      dialogVisible.value = false
      ElMessage.success("变更成功");
      getPage();
    } else {
      spinning.value = false;
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    console.log(error)
    spinning.value = false;
  })

}

</script>
<style>


.el-tree .el-tree-node.is-penultimate > .el-tree-node__children {
  display: flex;
  flex-direction: row;
  flex-flow: row wrap
}

.is-penultimate > .el-tree-node__children > div {
  padding: 0px;
  margin: 0px;
  width: 25%;
}
</style>